package cn.jx.cjm.security.common.handler;

import cn.jx.cjm.common.enums.BizExceptionEnum;
import cn.jx.cjm.security.common.util.ResponseUtils;
import cn.jx.cjm.security.support.SysUserSelfSupportService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {


    @Autowired
    private SysUserSelfSupportService sysUserSelfSupportService;

    @Autowired
    private ResponseUtils responseUtils;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        R<?> r;

        if (exception instanceof AccountExpiredException) {
            r = R.failed(BizExceptionEnum.AUTH_ACCOUNT_EXPIRED);
        } else if (exception instanceof CredentialsExpiredException) {
            r = R.failed(BizExceptionEnum.AUTH_PASSWORD_EXPIRED);
        } else if (exception instanceof UsernameNotFoundException) {
            r = R.failed(BizExceptionEnum.AUTH_USER_NOT_FOND);
        } else if (exception instanceof LockedException ) {
            r = R.failed(BizExceptionEnum.AUTH_ACCOUNT_LOCKED);
        } else {
            r = R.failed(BizExceptionEnum.AUTH_PASSWORD_ERROR);
            String username =  request.getParameter("username");
            sysUserSelfSupportService.addPasswordErrorTimes(username);
        }
        responseUtils.send(request, response, JSON.toJSONString(r));
    }
}
